<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Access\AuthorizationException;
use App\Models\User;
use App\Observers\UserObserver;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
        User::observe(UserObserver::class);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // dingoApi 异常处理
        \API::error(function (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) {
            abort(404);
        });
        //更改验证规则的状态码及消息提醒
        \API::error(function (\Illuminate\Validation\ValidationException $exception) {
            $data = $exception->validator->getMessageBag();
            $msg = collect($data)->first();
            if (is_array($msg)) {
                $msg = $msg[0];
            }
            return response()->json(['message' => $msg, 'status_code' => 422], 422);
        });
        // dingoApi 异常处理
        \API::error(function (\Spatie\Permission\Exceptions\UnauthorizedException $exception) {
            return response()->json(['message' => '没有权限', 'status_code' => 403], 403);
        });

        \API::error(function (AuthenticationException $exception) {
            abort(401, 'Unauthenticated');
        });

        \API::error(function (AuthorizationException $exception) {
            abort(403, 'Unauthorized.');
        });
    }
}
